﻿using DH.Core;
using DH.Data;
using DH.Entity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DH.Data.ORM.EF.Extensions;
using DH.Core.MapperHelper;
using DH.Service.ViewModels;
using CacheManager.Core;
using DH.Core.Extensions;
using DH.Core.Helper;
using System.Threading.Tasks;
using DH.Core.Exceptions;
using DH.Service.ViewModels.Dto;
using DH.Data.ORM.EF;
using Microsoft.EntityFrameworkCore;

namespace DH.Service.Domain
{
    public class OrganizeService: BaseService<OrganizeEntity, string>
    {
        protected IServiceCollection _serviceCollection;
        //protected ICacheManager<object> _cacheManager;

        public OrganizeService(IServiceCollection service, DbCoreUnitOfWork unitOfWork) : base(service,unitOfWork)
        {
            this._serviceCollection = service;
            //_cacheManager = service.BuildServiceProvider().GetService<ICacheManager<object>>() as BaseCacheManager<object>;
            //_cacheManager = CacheHelper.CustomManager;
        }

        public PagedData<OrganizeEntity> GetOrgsByQuery(string key,string orgParentId, Pagination page)
        {
            
            var orgQuery = GetAllSync() as IQueryable<OrganizeEntity>;
            orgQuery = orgQuery.Where(c=> c.Id != Guid.Empty.ToString()&&c.DeleteMark==false);
            if (!string.IsNullOrWhiteSpace(key))
            {
                orgQuery = orgQuery.Where(c => (c.EnCode == key || c.FullName == key)) ;
            }
            if (!string.IsNullOrEmpty(orgParentId))
            {
                var orgParent = GetSync(orgParentId);
                if (orgParent != null)
                {
                    orgQuery = orgQuery.Where(c=>c.IndexId.Contains(orgParent.IndexId)&&c.IndexId!=orgParent.Id);
                }
            }

            var tableEntityList = orgQuery.OrderBy(c=>c.IndexId).ThenBy(c=>c.SortIndex).ThenBy(c=>c.CreatedOn).TakePageData(page);
            return tableEntityList;
        }

        public   List<TreeSelectViewModel> GetSelectTreeDataList()
        {
            //var expiration = Global.Configuration["cacheConfig:redis:expiration"];
            var expirationStr = ConfigHelper.CacheExpiration;
            var expiration = Convert.ToInt32(expirationStr);
            //var dataList = new List<TreeSelectViewModel>();
            //从缓存中获取
            var timeSpan = new TimeSpan(0, 0, expiration, 0);
            return _cacheManager.Get(ConstHelper.OrgConst, ConstHelper.Region, timeSpan,() =>
            {
                return GetSelectTreeDatas("");
            });
        }

        public List<TreeSelectViewModel> GetTreeDataList()
        {
            //return GetSelectTreeDataList();
            var dataList = new List<TreeSelectViewModel>();
            var treeDataQuable = GetAllSync().Where(c => c.EnabledMark == true && c.DeleteMark == false);
            treeDataQuable = treeDataQuable.Where(c => c.IndexId.Contains("0.")).OrderBy(c => c.IndexId).ThenBy(c => c.CreatedOn);
            dataList = treeDataQuable.Select(c => {
                var orgViewModel = DHMapper.Map<OrganizeEntity, TreeSelectViewModel>(c);
                orgViewModel.text = c.FullName;
                //orgViewModel.iconCls = GetIcon(c.CategoryId);
                //orgViewModel.children = GetChildrenSelectTrees(c.Id);
                return orgViewModel;
            }).ToList();

            return dataList;

        }
        public List<TreeSelectViewModel> GetCacheTreeDataList()
        {
            var expirationStr = ConfigHelper.CacheExpiration;
            var expiration = Convert.ToInt32(expirationStr);
            TimeSpan timeSpan = new TimeSpan(0, 0, expiration, 0);
            return _cacheManager.Get(ConstHelper.OrgAllObjConst, ConstHelper.Region, timeSpan, () =>
            {
                return GetTreeDataList();
            });
        }
        public List<TreeSelectViewModel> UpdateTreeDataList()
        {
            var expirationStr = ConfigHelper.CacheExpiration;
            var expiration = Convert.ToInt32(expirationStr);
            TimeSpan timeSpan = new TimeSpan(0, 0, expiration, 0);
            return _cacheManager.Update(ConstHelper.OrgAllObjConst, ConstHelper.Region, timeSpan, () =>
            {
                return GetTreeDataList();
            });
        }
        public List<TreeSelectViewModel> UpDateSelectTreeDataList()
        {
            var expirationStr = ConfigHelper.CacheExpiration;
            var expiration = Convert.ToInt32(expirationStr);
            TimeSpan timeSpan = new TimeSpan(0, 0, expiration, 0);
            return _cacheManager.Update(ConstHelper.OrgConst, ConstHelper.Region, timeSpan, () =>
            {
                return GetSelectTreeDatas("");
            });
        }
        public List<TreeSelectViewModel> GetSelectTreeDatas(string parentId)
        {
            var dataList = new List<TreeSelectViewModel>();

            var treeDataQuable = GetAllSync().Where(c=>c.EnabledMark==true&&c.DeleteMark==false);
           
            if (string.IsNullOrWhiteSpace(parentId))
            {
                parentId = "0";
            }
           
            treeDataQuable = treeDataQuable.Where(c => c.ParentId == parentId).OrderBy(c => c.IndexId).ThenBy(c=>c.CreatedOn);
            dataList = treeDataQuable.Select(c => {
                var orgViewModel = DHMapper.Map<OrganizeEntity, TreeSelectViewModel>(c);
                orgViewModel.text = c.FullName;
                orgViewModel.iconCls = GetIcon(c.CategoryId);
                orgViewModel.children = GetChildrenSelectTrees(c.Id);
                return orgViewModel;
            }).ToList();

            return dataList;

        }
        
        public List<TreeSelectViewModel> GetChildrenSelectTrees(string parentId)
        {
            var dataList = new List<TreeSelectViewModel>();
            var treeDataQuable = GetAllSync().Where(c => c.EnabledMark == true && c.DeleteMark == false);
            dataList= treeDataQuable.Where(c => c.ParentId == parentId).OrderBy(c => c.IndexId).ThenBy(c => c.CreatedOn).Select(c=> {
                var orgViewModel = DHMapper.Map<OrganizeEntity, TreeSelectViewModel>(c);
                orgViewModel.text = c.FullName;
                orgViewModel.iconCls = GetIcon(c.CategoryId);
                orgViewModel.children = GetChildrenSelectTrees(c.Id);
                return orgViewModel;
            }).ToList();
            return dataList;
        }

        private string GetIcon(string type)
        {

            var className = "tree-folder";
            switch (type)
            {
                case "ROOT":
                    className = "tree-root";
                    break;
                case "Group":
                    className = "tree-group";
                    break;
                case "Company":
                    className = "tree-company";
                    break;
                case "Department":
                    className = "tree-depment";
                    break;
                case "WorkGroup":
                    className = "tree-work-group";
                    break;
                case "User":
                    className = "tree-user";
                    break;


            }
            return className;

        }


        public OrganizeEntity Add(OrganizeViewModel viewModel)
        {
            //更新treeNode排序IndexId
            OrganizeEntity model;
            model = DHMapper.Map<OrganizeViewModel,OrganizeEntity>(viewModel);
            model.Id = Guid.NewGuid().ToString();
            model.Layers = 0;
            model.UpdatedOn = DateTimeOffset.Now;
            model.DeleteMark = false;
            model.DeletedBy = "";
            model.CreatedOn = DateTimeOffset.Now;
            model.AllowDelete = false;
            model.AllowEdit = true;

            //model.IndexId= ChangeNodeIndex(model.ParentId,model.Id,model.SortIndex);
            ChangNode(model);
            

            //是否有已存在排序
            var checkExistSort = CheckExistSortIndex(model.ParentId,model.SortIndex);
            if (checkExistSort)
            {
                ChangeExistSort(model.ParentId,model.SortIndex);
            }

            model = InsertSync(model);


            return model;
        }
        public OrganizeEntity Update(OrganizeViewModel viewModel)
        {
            var oldObj = GetSync(viewModel.Id);
            if (oldObj == null) {
                throw new EntityNotFoundException(nameof(oldObj), 0);
            }
            //旧对象
            var oldEntityIndexId = oldObj.IndexId;
            var oldEntitySortIndex = oldObj.SortIndex;
            var oldEntityParentId = oldObj.ParentId;

            //是否有已存在排序
            var checkExistSort = CheckExistSortIndex(viewModel.ParentId, viewModel.SortIndex, viewModel.Id);
            if (checkExistSort)
            {
                ChangeExistSort(viewModel.ParentId, viewModel.SortIndex);
            }

            var entity=DHMapper.Map<OrganizeViewModel, OrganizeEntity>(viewModel, oldObj);//oldObj经过mapper后和entity一样
            

            if (oldEntityParentId != entity.ParentId)//父节点更换了
            {
                //entity.IndexId = ChangeNodeIndex(entity.ParentId, entity.Id, entity.SortIndex);
                ChangNode(entity);
            }
            else if(oldEntitySortIndex!=entity.SortIndex)//排序号更换了
            {
                
                var parentNode = GetSync(entity.ParentId);
                if (parentNode != null)
                {
                    if (entity.SortIndex == 0)
                    {
                        var maxIndex = GetMaxIndexInNode(entity.ParentId,entity.Id);
                        entity.IndexId = parentNode.IndexId + maxIndex + ".";
                    }
                    else
                    {
                        entity.IndexId = parentNode.IndexId + entity.SortIndex + ".";
                    }
                }
                else
                {
                    throw new EntityNotFoundException(typeof(OrganizeEntity).Name, entity.ParentId);
                }
                    
            }
            
            entity = UpdateSync(entity);


            var childNodes = GetAllSync().Where(c => c.DeleteMark == false && c.EnabledMark == true && c.IndexId.Contains(oldEntityIndexId) && c.Id != entity.Id).OrderBy(c => c.IndexId).ToList();
            foreach (var node in childNodes)
            {
                
                node.IndexId = node.IndexId.Replace(oldEntityIndexId, entity.IndexId);
                UpdateSync(node);
            }

            return entity;
        }

        public void Delete(string[] ids)
        {
            var models = GetByQuery(c => ids.Contains(c.Id));
            DeleteSync(models);
        }

        public bool CheckExistSortIndex(string parentId,int sortIndex,string Id="")
        {
            var res = false;
            var organizeObj = GetAllSync().Where(c => c.ParentId == parentId && c.SortIndex == sortIndex && c.EnabledMark == true && c.DeleteMark == false);
            if (!string.IsNullOrWhiteSpace(Id))
            {
                organizeObj = organizeObj.Where(c=>c.Id != Id);
            }
            
            if (organizeObj.Count()>0)
            {
                res = true;
            }

            return res;
        }

        private string  ChangeNodeIndex(string parentId,string Id)
        {
            var indexIdStr = "";
            

            //查找父节点下所有子节点最大IndexId
            var maxInNode = 0;
            var siblings = GetAllSync().Where(c => c.ParentId == parentId && c.Id != Id).ToList();
            foreach (var sb in siblings)
            {
                var indexId = int.Parse(sb.IndexId.TrimEnd('.').Split('.').Last());
                
                if (maxInNode<indexId)
                {
                    maxInNode = indexId;
                }
            }            
            maxInNode = maxInNode + 1;

            //parentName
            //IndexId
            if (!string.IsNullOrWhiteSpace(parentId) && parentId != Guid.Empty.ToString())
            {
                var parentNode = GetSync(parentId);
                if (parentNode!=null)
                {
                    //model.ParentName = parentNode.FullName;
                    indexIdStr = parentNode.IndexId + maxInNode+".";
                }
                else
                {
                    throw new EntityNotFoundException(typeof(OrganizeEntity).Name, parentId);
                }

            }
            else
            {
                //model.ParentName = "根节点";
                indexIdStr =  "0." + maxInNode+".";
            }

            return indexIdStr;
            
        }

        private string ChangeNodeIndex(string parentId, string Id,int sortIndex)
        {
            var indexIdStr = "";

            //查找父节点下所有子节点最大IndexId
            var maxInNode = 0;

            
            if (sortIndex!=0)
            {
                maxInNode = sortIndex;
            }
            else
            {
                //var siblings = GetAllSync().Where(c => c.ParentId == parentId && c.Id != Id).ToList();
                //foreach (var sb in siblings)
                //{
                //    var indexId = int.Parse(sb.IndexId.TrimEnd('.').Split('.').Last());

                //    if (maxInNode < indexId)
                //    {
                //        maxInNode = indexId;
                //    }
                //}
                maxInNode = GetMaxIndexInNode(parentId,Id);
                maxInNode = maxInNode + 1;
            }

            //parentName
            //IndexId
            if (!string.IsNullOrWhiteSpace(parentId) && parentId != Guid.Empty.ToString())
            {
                var parentNode = GetSync(parentId);
                if (parentNode != null)
                {
                    //model.ParentName = parentNode.FullName;
                    indexIdStr = parentNode.IndexId + maxInNode + ".";
                }
                else
                {
                    throw new EntityNotFoundException(typeof(OrganizeEntity).Name, parentId);
                }

            }
            else
            {
                //model.ParentName = "根节点";
                indexIdStr = "0." + maxInNode + ".";
            }

            return indexIdStr;

        }
        private void ChangNode(OrganizeEntity model)
        {
           

            //查找父节点下所有子节点最大IndexId
            var maxInNode = 0;


            if (model.SortIndex != 0)
            {
                maxInNode = model.SortIndex;
            }
            else
            {
                var siblings = GetAllSync().Where(c => c.ParentId == model.ParentId && c.Id != model.Id).ToList();
                foreach (var sb in siblings)
                {
                    var indexId = int.Parse(sb.IndexId.TrimEnd('.').Split('.').Last());

                    if (maxInNode < indexId)
                    {
                        maxInNode = indexId;
                    }
                }
                maxInNode = maxInNode + 1;

                model.SortIndex = maxInNode;
            }

            //parentName
            //IndexId
            if (!string.IsNullOrWhiteSpace(model.ParentId) && model.ParentId != Guid.Empty.ToString())
            {
                var parentNode = GetSync(model.ParentId);
                if (parentNode != null)
                {
                    //model.ParentName = parentNode.FullName;
                   model.IndexId = parentNode.IndexId + maxInNode + ".";
                }
                else
                {
                    throw new EntityNotFoundException(typeof(OrganizeEntity).Name, model.ParentId);
                }

            }
            else
            {
                //model.ParentName = "根节点";
                model.IndexId = "0." + maxInNode + ".";
            }

           
        }

        /// <summary>
        /// 获取节点下排序号
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="sortIndex"></param>
        /// <returns></returns>
        public string ChangNodeIndex(string parentId,out int sortIndex)
        {
            var maxIndexId = "";
            //查找父节点下所有子节点最大IndexId
            var maxInNode = 0;
            var siblings = GetAllSync().Where(c => c.ParentId == parentId).ToList();
            foreach (var sb in siblings)
            {
                var indexId = int.Parse(sb.IndexId.TrimEnd('.').Split('.').Last());

                if (maxInNode < indexId)
                {
                    maxInNode = indexId;
                }
            }
            maxInNode = maxInNode + 1;
            sortIndex = maxInNode;

            var parentNode = GetSync(parentId);
            if (parentNode != null)
            {
                //model.ParentName = parentNode.FullName;
                maxIndexId = parentNode.IndexId + maxInNode + ".";
            }
            else
            {
                maxIndexId = "0." + maxIndexId + ".";
            }
            return maxIndexId;
        }

        public string GetNodesInParents(string parentIds)
        {
            var maxIndexId = string.Empty;
            var sortIndex = 0;
            var parentArr = parentIds.Split(',');
            
            foreach (var pid in parentArr)
            {
               var currentMaxIndexId=  ChangNodeIndex(pid,out sortIndex);
                maxIndexId += currentMaxIndexId+",";
            }

            maxIndexId = maxIndexId.Substring(0,maxIndexId.Length-1);

            return maxIndexId;
        }

        /// <summary>
        /// 修改原有序号
        /// 如果序号重复，管理员允许的情况下，保存新序号，旧序号全部重写当前组内最大序号
        /// 例如:
        /// 团贷网 0
        ///    技术中心 node序号 0.1  排序号 1
        ///       OA组  node序号 0.1.1 排序号1
        ///    财务中心 node序号 0.2  排序号2
        ///       出纳  Node序号 0.2.1  排序号为1
        /// 现在将财务中心序号调整1,则组内（团贷网）下已存在序号为1的技术中心就调整为node 序号1.3.1,排序号为1
        /// 调整后为
        /// 团贷网 0
        ///    技术中心 node序号 0.3  排序号 3
        ///       OA组  node序号 0.3.1 排序号1
        ///    财务中心 node序号 0.1  排序号1
        ///       出纳  Node序号 0.1.1  排序号为1
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="sortIdndex"></param>
        private void ChangeExistSort(string parentId,int sortIdndex)
        {
            var parentNode = GetSync(parentId);
            if (parentNode!=null)
            {
                var maxSortInParentNodeObj = GetAllSync().Where(c => c.EnabledMark == true && c.DeleteMark == false && c.ParentId == parentId);
                var maxSortInParentNode = maxSortInParentNodeObj.OrderByDescending(c => c.SortIndex).First().SortIndex;
                var currentObj = GetAllSync().Where(c => c.EnabledMark == true && c.DeleteMark == false && c.ParentId == parentId && c.SortIndex == sortIdndex).First();
                if (currentObj != null)
                {
                    var currentObjOldIndex = currentObj.IndexId;
                    currentObj.SortIndex = maxSortInParentNode + 1;
                    currentObj.IndexId = parentNode.IndexId + currentObj.SortIndex + ".";
                    UpdateSync(currentObj);

                    var childsInCurrentObj = GetAllSync().Where(c=>c.DeleteMark==false&&c.EnabledMark==true&& c.IndexId.Contains(currentObjOldIndex)&&c.Id!= currentObj.Id).ToList();
                    foreach (var child in childsInCurrentObj)
                    {
                        child.IndexId = child.IndexId.Replace(currentObjOldIndex,currentObj.IndexId);
                        UpdateSync(child);
                    }
                }
            }
            
        }

        //获取节点最大排序号
        private int GetMaxIndexInNode(string parentId,string Id)
        {
            var maxInNode = 0;
            var siblings = GetAllSync().Where(c => c.ParentId == parentId && c.Id != Id).ToList();
            foreach (var sb in siblings)
            {
                var indexId = int.Parse(sb.IndexId.TrimEnd('.').Split('.').Last());

                if (maxInNode < indexId)
                {
                    maxInNode = indexId;
                }
            }
            return maxInNode;
        }


        public List<OrgDto> GetFullPathOrg()
        {
            var sql = string.Format(@"WITH cte_org AS (
                                          SELECT  Cast(FullName as nvarchar(max)) AS  FullName,
                                              FullName AS Name,
	                                          Id,
	                                          ParentId 
	                                          FROM Sys_Organize WHERE EnabledMark=1 AND DeleteMark=0 AND Id='00000000-0000-0000-0000-000000000000'
                                          UNION ALL
                                          SELECT 
                                                 (
                                                  (
                                                     CASE sysOrg.ParentId
                                                          WHEN '' THEN ''
                                                          ELSE cteSysOrg.FullName+'/'
                                                     END 
                                                  ) + sysOrg.FullName
                                                 ) AS FullName,
                                                 sysOrg.FullName AS Name,
                                                 sysOrg.Id,
                                                 sysOrg.ParentId
          
                                          FROM Sys_Organize AS sysOrg
                                                        INNER JOIN cte_org AS cteSysOrg
                                                        ON cteSysOrg.Id=sysOrg.ParentId
                                                        WHERE EnabledMark=1 AND DeleteMark=0
                                        )
                                        SELECT * FROM cte_org  ");
            var res = this._repository.Context.Database.SqlQuery<OrgDto>(sql);
            return res.ToList();

        }

        /// <summary>
        /// 根据组织id获取组织名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetOrgNameById(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var orgName = "";
                var ids = id.Split(',');
                foreach (var i in ids)
                {
                    orgName += GetSync(i) == null ? "" : GetSync(i).FullName + ",";
                }
                orgName = orgName.Substring(0, orgName.Length - 1);

                return orgName;
            }
            else {
                return "";
            }
            
        }

        #region 异步操作
        public async  Task<PagedData<OrganizeEntity>> GetOrgsByQueryAsync(string key, string orgParentId, Pagination page)
        {

            var orgQuery = (await GetAllAsync()) as IQueryable<OrganizeEntity>;
            orgQuery = orgQuery.Where(c => c.Id != Guid.Empty.ToString() && c.DeleteMark == false);
            if (!string.IsNullOrWhiteSpace(key))
            {
                orgQuery = orgQuery.Where(c => (c.EnCode == key || c.FullName == key));
            }
            if (!string.IsNullOrEmpty(orgParentId))
            {
                var orgParent = GetSync(orgParentId);
                if (orgParent != null)
                {
                    orgQuery = orgQuery.Where(c => c.IndexId.StartsWith(orgParent.IndexId) && c.IndexId != orgParent.Id);
                }
            }

            var tableEntityList = orgQuery.OrderBy(c => c.IndexId).ThenBy(c => c.SortIndex).ThenBy(c => c.CreatedOn).TakePageData(page);
            return tableEntityList;
        }

        public async Task<OrganizeEntity> AddAsync(OrganizeViewModel viewModel)
        {
            //更新treeNode排序IndexId
            OrganizeEntity model;
            model = DHMapper.Map<OrganizeViewModel, OrganizeEntity>(viewModel);
            model.Id = Guid.NewGuid().ToString();
            model.Layers = 0;
            model.UpdatedOn = DateTimeOffset.Now;
            model.DeleteMark = false;
            model.DeletedBy = "";
            model.CreatedOn = DateTimeOffset.Now;
            model.AllowDelete = false;
            model.AllowEdit = true;

            //model.IndexId= ChangeNodeIndex(model.ParentId,model.Id,model.SortIndex);
            ChangNode(model);


            //是否有已存在排序
            var checkExistSort = CheckExistSortIndex(model.ParentId, model.SortIndex);
            if (checkExistSort)
            {
                ChangeExistSort(model.ParentId, model.SortIndex);
            }

            model =await InsertAsync(model);
            
            return model;
        }

        public async Task<OrganizeEntity> UpdateAsync(OrganizeViewModel viewModel)
        {
            var oldObj = await  GetAsync(viewModel.Id);
            if (oldObj == null)
            {
                throw new EntityNotFoundException(nameof(oldObj), 0);
            }
            //旧对象
            var oldEntityIndexId = oldObj.IndexId;
            var oldEntitySortIndex = oldObj.SortIndex;
            var oldEntityParentId = oldObj.ParentId;
            var oldEntityName = oldObj.FullName;
            

            //是否有已存在排序
            var checkExistSort = CheckExistSortIndex(viewModel.ParentId, viewModel.SortIndex, viewModel.Id);
            if (checkExistSort)
            {
                ChangeExistSort(viewModel.ParentId, viewModel.SortIndex);
            }

            var entity = DHMapper.Map<OrganizeViewModel, OrganizeEntity>(viewModel, oldObj);//oldObj经过mapper后和entity一样


            if (oldEntityParentId != entity.ParentId)//父节点更换了
            {
                //entity.IndexId = ChangeNodeIndex(entity.ParentId, entity.Id, entity.SortIndex);
                ChangNode(entity);
            }
            else if (oldEntitySortIndex != entity.SortIndex)//排序号更换了
            {

                var parentNode = GetSync(entity.ParentId);
                if (parentNode != null)
                {
                    if (entity.SortIndex == 0)
                    {
                        var maxIndex = GetMaxIndexInNode(entity.ParentId, entity.Id);
                        entity.IndexId = parentNode.IndexId + maxIndex + ".";
                    }
                    else
                    {
                        entity.IndexId = parentNode.IndexId + entity.SortIndex + ".";
                    }
                }
                else
                {
                    throw new EntityNotFoundException(typeof(OrganizeEntity).Name, entity.ParentId);
                }

            }

            entity =await UpdateAsync(entity);


            var childNodes = GetAllSync().Where(c => c.DeleteMark == false && c.EnabledMark == true && c.IndexId.Contains(oldEntityIndexId) && c.Id != entity.Id).OrderBy(c => c.IndexId).ToList();
            foreach (var node in childNodes)
            {

                node.IndexId = node.IndexId.Replace(oldEntityIndexId, entity.IndexId);
                await UpdateAsync(node);
            }

            //如果组织改了名字
            if (oldEntityName!= viewModel.FullName)
            {
                //修改所有子组织的组织名称
                await UpdateChildrenOrgName(viewModel.ParentId,viewModel.FullName);
                //修改所有用户的组织名称
                await UpdateUsersOrgName(viewModel.ParentId,oldEntityName,viewModel.FullName);
            }


            return entity;
        }
        /// <summary>
        /// 更新组织架构下所有子组织的父组织名称
        /// </summary>
        /// <param name="parentOrgId"></param>
        /// <param name="newParentOrgName"></param>
        /// <returns></returns>
        private async Task UpdateChildrenOrgName(string parentOrgId,string newParentOrgName)
        {
            var res = await GetByQueryAsync(c=>c.ParentId==parentOrgId&&c.EnabledMark==true&&c.DeleteMark==false);
            foreach (var r in res)
            {
                r.ParentName = newParentOrgName;
            }
            await this._unitOfWork.ExecuteAndCommitAsync(()=> {
                return this._repository.UpdateAsync(res);
            });
            
        }
        /// <summary>
        /// 组织架构名称修改后，修改所有用户的旧组织名称为新组织名称
        /// </summary>
        /// <param name="parentOrgId"></param>
        /// <param name="oldParentOrgName"></param>
        /// <param name="newParentOrgName"></param>
        /// <returns></returns>
        private async Task UpdateUsersOrgName(string parentOrgId,string oldParentOrgName,string newParentOrgName)
        {
            var sql = string.Format(@" UPDATE Sys_User SET OrgName=replace(OrgName,'{0}','{1}') WHERE DH_OrganizeId like '%{2}%' ", oldParentOrgName,newParentOrgName,parentOrgId);

            await this._repository.Context.Database.ExecuteSqlCommandAsync(sql);
        }

        public async Task DeleteAsync(string[] ids)
        {
            var models =await GetByQueryAsync(c => ids.Contains(c.Id));
            await DeleteAsync(models);
        }

        public async  Task<List<TreeSelectViewModel>> GetTreeDataListAsync()
        {
            
            var dataList = new List<TreeSelectViewModel>();
            var treeDataQuable =(await GetAllAsync()).Where(c => c.EnabledMark == true && c.DeleteMark == false);
            treeDataQuable = treeDataQuable.Where(c => c.IndexId.Contains("0.")).OrderBy(c => c.IndexId).ThenBy(c => c.CreatedOn);
            dataList = treeDataQuable.Select(c => {
                var orgViewModel = DHMapper.Map<OrganizeEntity, TreeSelectViewModel>(c);
                orgViewModel.text = c.FullName;
                return orgViewModel;
            }).ToList();

            return dataList;

        }
        public async Task<List<TreeSelectViewModel>> GetCacheTreeDataListAsync()
        {
            var expirationStr = ConfigHelper.CacheExpiration;
            var expiration = Convert.ToInt32(expirationStr);
            TimeSpan timeSpan = new TimeSpan(0, 0, expiration, 0);
            return await _cacheManager.GetAsync(ConstHelper.OrgAllObjConst, ConstHelper.Region, timeSpan, () =>
            {
                return  GetTreeDataListAsync();
            });
        }
        #endregion

    }
}
